package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.hsp.system.repository.AtendenteARSRepository; 
import br.com.hsp.users.AtendenteARS;

@ManagedBean
public class AtendenteARSBean {

	private AtendenteARS atendenteARS = new AtendenteARS();
	
	private List<AtendenteARS> atendenteARSs; 

	public void add() {
		EntityManager manager = this.getManager();
		AtendenteARSRepository atendenteARSRepository = new AtendenteARSRepository(manager);

		if (this.atendenteARS.getId() == null) {
			atendenteARSRepository.add(this.atendenteARS);
		} else {
			atendenteARSRepository.atualiza(this.atendenteARS);
		}
		this.atendenteARS = new AtendenteARS();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		AtendenteARSRepository repository = new AtendenteARSRepository(manager);
		this.atendenteARS = repository.procura(id);

	}
	

	public void remove() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		AtendenteARSRepository repository = new AtendenteARSRepository(manager);
		repository.remove(id);
		this.atendenteARS = null;
		this.atendenteARSs = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<AtendenteARS> getAtendenteARSs() {
		if (this.atendenteARSs == null) {
			EntityManager manager = this.getManager();
			AtendenteARSRepository repository = new AtendenteARSRepository(manager);
			this.atendenteARSs = repository.getLista();
		}
		return this.atendenteARSs;
	}

	public AtendenteARS getAtendenteARS() {
		return atendenteARS;
	}

	public void setAtendenteARS(AtendenteARS atendenteARS) {
		this.atendenteARS = atendenteARS;
	}

}
